const app = new Vue({
  // 使用render函数代替模板编译
  render: function(h) {
    return h('div', { class: 'layout' }, [
      // 侧边栏
      h('div', { class: 'sidebar' }, [
        h('div', {
          class: ['menu-item', this.showReceiveForm ? 'active' : ''],
          on: { click: () => { this.showReceiveForm = true; this.show1688SyncForm = false; } }
        }, ['礼服单件收货']),
        h('div', {
          class: ['menu-item', this.show1688SyncForm ? 'active' : ''],
          on: { click: () => { this.show1688SyncForm = true; this.showReceiveForm = false; } }
        }, ['1688产品同步'])
      ]),
      // 内容区
      h('div', { class: 'content' }, [
        this.showReceiveForm ? h('div', { class: 'form-container' }, [
          h('h3', ['礼服单件收货']),
          // 箱唛号输入
          h('div', { class: 'form-item' }, [
            h('label', ['箱唛号：']),
            h('input', {
              attrs: { type: 'text', placeholder: '请输入箱唛号' },
              domProps: { value: this.formData.boxMarkNo },
              on: { input: (e) => this.formData.boxMarkNo = e.target.value }
            })
          ]),
          // 子订单号输入
          h('div', { class: 'form-item' }, [
            h('label', ['子订单号：']),
            h('input', {
              attrs: { type: 'text', placeholder: '请输入子订单号' },
              domProps: { value: this.formData.subOrderNo },
              on: { input: (e) => this.formData.subOrderNo = e.target.value }
            })
          ]),
          // 提交按钮
          h('button', {
            class: 'submit-btn',
            on: { click: this.submitForm }
          }, ['提交'])
        ]) : null,
        this.show1688SyncForm ? h('div', { class: 'form-container' }, [
          h('h3', ['1688产品同步']),
          // 1688产品ID输入
          h('div', { class: 'form-item' }, [
            h('label', ['1688产品ID：']),
            h('input', {
              attrs: { type: 'text', placeholder: '请输入1688产品ID' },
              domProps: { value: this.syncData.productId },
              on: { input: (e) => this.syncData.productId = e.target.value }
            })
          ]),
          // 确认拉取按钮
          h('button', {
            class: 'submit-btn',
            on: { click: this.submitSyncForm }
          }, ['确认拉取'])
        ]) : null
      ])
    ])
  },
  data: {
    showReceiveForm: true,
    show1688SyncForm: false,
    formData: {
      boxMarkNo: '',
      subOrderNo: ''
    },
    syncData: {
      productId: ''
    }
  },
  async mounted() {
    // 从storage中恢复表单数据
    const result = await chrome.storage.local.get(['formData'])
    if (result.formData) {
      this.formData = result.formData
    }
  },
  watch: {
    // 监听表单数据变化并保存到storage
    formData: {
      handler(newValue) {
        chrome.storage.local.set({ formData: newValue })
      },
      deep: true
    }
  },
  methods: {
    async submitForm() {
      if (!this.formData.boxMarkNo || !this.formData.subOrderNo) {
        alert('箱唛号和子订单号不能为空！')
        return
      }

      try {
        // 获取cookie
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
        const cookie = await chrome.cookies.get({
          url: 'https://oa.huaperfect.com',
          name: 'micro_token'
        })

        if (!cookie) {
          alert('请先登录 OA 系统然后再操作！')
          return
        }

        // 发送请求
        //https://oa.huaperfect.com/api/store/
        const response = await fetch('https://api.oa.huaperfect.com/store/robes/check_goods/reset/package', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookie.value}`
          },
          body: JSON.stringify({
            box_mark_no: this.formData.boxMarkNo,
            sub_order_no: this.formData.subOrderNo
          })
        })

        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          alert(result.msg || '操作成功')
          // 重置表单并清除storage中的数据
          this.formData.boxMarkNo = ''
          this.formData.subOrderNo = ''
          chrome.storage.local.remove(['formData'])
        } else {
          throw new Error(result.msg || '操作失败')
        }
      } catch (error) {
        alert(`操作失败: ${error.message}`)
      }
    },
    async submitSyncForm() {
      if (!this.syncData.productId) {
        alert('1688 产品 ID 不能为空！')
        return
      }

      try {
        // 获取cookie （不需要登录）
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
        // const cookie = await chrome.cookies.get({
        //   url: 'https://oa.huaperfect.com',
        //   name: 'micro_token'
        // })

        // if (!cookie) {
        //   alert('请先登录 OA 系统然后再操作！')
        //   return
        // }

        // 发送请求
        const response = await fetch(`https://purchase.oa.huaperfect.com/api/purchase-new/1688/product/sync?product_id=${this.syncData.productId}`, {
          method: 'GET',
          headers: {
            // 'Authorization': `Bearer ${cookie.value}`
          }
        })

        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`)
        }

        alert('操作成功')
          // 重置表单
          this.syncData.productId = ''
      } catch (error) {
        alert(`操作失败: ${error.message}`)
      }
    }
  }
})

// 在DOM加载完成后手动挂载Vue实例
document.addEventListener('DOMContentLoaded', () => {
  app.$mount('#app')
})